﻿using System;
using System.Globalization;
using YourLastOptionsDialog.Controls;

namespace YourLastOptionsDialog.ViewModels.Options
{
    /// <summary>
    /// Validates a string input as floating point value.
    /// </summary>
    public class FloatValidator : IValidator
    {
        private readonly double _minimum;
        private readonly double _maximum;

        /// <summary>
        /// Gets or sets the validation error message.
        /// </summary>
        public string ValidationErrorMessage
        {
            get;
            set;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="FloatValidator"/> class.
        /// </summary>
        /// <param name="minimum">The allowed minimum to use for validation.</param>
        /// <param name="maximum">The allowed maximum to use for validation.</param>
        public FloatValidator(double minimum, double maximum)
        {
            _minimum = minimum;
            _maximum = maximum;
        }

        #region Implementation of IValidator

        /// <summary>
        /// Validates the specified input and returns a <see cref="ValidationResult"/> with the outcome of the validation.
        /// </summary>
        /// <param name="input">The input value to validate.</param>
        /// <returns>
        /// The result of the validation.
        /// </returns>
        public ValidationResult Validate(string input)
        {
            // we're arbitrarily limiting this here to doubles,
            // which means it might become a problem with decimals.
            // For the moment this should be ok though.
            double converted;
            bool isValid = double.TryParse(input, NumberStyles.Float, CultureInfo.CurrentCulture, out converted);
            if (!isValid)
            {
                return new ValidationResult(false, ValidationErrorMessage);
            }

            // try to convert
            try
            {
                if (converted < _minimum || converted > _maximum)
                {
                    return new ValidationResult(false, ValidationErrorMessage);
                }
            }
            catch (Exception)
            {
                return new ValidationResult(false, ValidationErrorMessage);
            }

            return ValidationResult.Success;
        }

        #endregion
    }
}
